import Food  from "./modules/Food";
import Snake from "./modules/Snake";
import Score  from "./modules/Score";
class Game {
   // 蛇
   snake: Snake;
   // 食物
   food: Food;
   // 记分牌
   score: Score;

    direction: string = ''

    isLive = true
    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.score = new Score()

        this.init()
    }

    init() {
        document.addEventListener('keydown', this.keyHandler.bind(this))
        this.run()
    }
    keyHandler(event: KeyboardEvent) {
        // console.log(event.key);

        this.direction = event.key
    }

    run() {
        let x = this.snake.X
        let y = this.snake.Y

        switch(this.direction){
            case "ArrowUp":
            case "Up":
                y -= 10
                break;
            case "ArrowDown":
            case "Down":
                y += 10
                break;
            case "ArrowLeft":
            case "Left":
                x -= 10
                break;
            case "ArrowRight":
            case "Right":
                x += 10
                break;
        }

        // 检查是否吃到食物
        this.checkEat(x, y)
           
        try {
            this.snake.X = x
            this.snake.Y = y
        } catch(e) {
            alert("Game over!")
            this.isLive = false
        }
        
        // 当蛇活着才会继续进行移动
        this.isLive && setTimeout(this.run.bind(this), 300 - (this.score.level -1)*30)
    }

    checkEat(x: number, y: number) {
        if(x === this.food.X && y === this.food.Y) {
            this.food.change()
            this.score.addScore()
            this.snake.addBody()
        }
    }
}

export default Game